<?php
// +----------------------------------------------------------------------
// | 07FLYSAAS [基于ThinkPHP5.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2025-2035 http://www.07fly.xyz
// +----------------------------------------------------------------------
// | Professional because of focus  Persevering because of happiness
// +----------------------------------------------------------------------
// | Author: 开发人生 <goodkfrs@qq.com>
// +----------------------------------------------------------------------


namespace app\plat\logic;

/**
 * 角色逻辑
 */
class TenRole extends PlatBase
{
    /**
     * 角色列表
     */
    public function getTenRoleList($where = [], $field = true, $order = 'sort asc', $paginate = DB_LIST_ROWS)
    {
        return $this->modelTenRole->getList($where, $field, $order, $paginate);
    }

    /**
     * 角色添加
     */
    public function tenRoleAdd($data = [])
    {
        $validate_result = $this->validateTenRole->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenRole->getError()];
        }
        $url = url('show');
        $result = $this->modelTenRole->setInfo($data);
        $result && ten_log('新增', '新增角色，name：' . $data['name']);
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelTenRole->getError()];
    }

    /**
     * 角色编辑
     */
    public function tenRoleEdit($data = [])
    {
        $validate_result = $this->validateTenRole->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenRole->getError()];
        }

        $url = url('authList');

        $result = $this->modelTenRole->setInfo($data);

        $result && ten_log('编辑', '编辑角色，name：' . $data['name']);

        return $result ? [RESULT_SUCCESS, '编辑成功', $url] : [RESULT_ERROR, $this->modelTenRole->getError()];
    }

    /**
     * 角色删除
     */
    public function tenRoleDel($data = [])
    {
        if (empty($data['id'])) {
            throw_response_error('参数错误');
        }
        $where['id'] = ['in', $data['id']];
        $result = $this->modelTenRole->deleteInfo($where, true);

        $where2['ten_role_id'] = ['in', $data['id']];
        $result && $this->modelTenRoleMenu->deleteInfo($where2, true);

        $result && ten_log('删除', '删除角色，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '角色删除成功'] : [RESULT_ERROR, $this->modelTenRole->getError()];
    }

    /**
     * 获取角色信息
     */
    public function getTenRoleInfo($where = [], $field = true)
    {
        $info = $this->modelTenRole->getInfo($where, $field);
        if (!empty($info)) {
            $info['ten_menu_ids'] = $this->modelTenRoleMenu->getColumn(['ten_role_id' => $info['id']], 'ten_menu_id');
        }
        return $info;
    }

    /**
     * 设置角色权限节点
     */
    public function setRoleMenuAuth($data = [])
    {
        if (empty($data['menu_ids']) || empty($data['id'])) {
            throw_response_error('参数错误');
        }
        $menuIds = $data['menu_ids'];
        $updata = [];
        foreach ($menuIds as $menuId) {
            $updata[] = [
                'ten_tenant_id' => TEN_TENANT_ID,
                'ten_role_id' => $data['id'],
                'ten_menu_id' => $menuId
            ];
        }
        $updata && $this->modelTenRoleMenu->deleteInfo(['ten_role_id' => $data['id']], true);
        $result = $this->modelTenRoleMenu->setList($updata);
        $result && ten_log('授权', '设置角色权限，id：' . $data['id']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '设置成功', $url] : [RESULT_ERROR, $this->modelTenModule->getError()];
    }

    /**
     * 选择角色
     */
    public function selectRoleAuthList($auth_list = [], $user_auth_ids = [])
    {
        foreach ($auth_list as &$info) {
            in_array($info['id'], $user_auth_ids) ? $info['tag'] = 'active' : $info['tag'] = '';
        }
        return $auth_list;
    }

    /**
     * 递归更新下级权限节点，确保下级权限不能超越上级
     * 若上级某权限被收回，则下级对应的权限同样被收回
     * 按会员更新
     */
    public function updateSubAuthByUser($sys_user_id = 0)
    {

        $auth_list = $this->logicTenUserRole->getUserAuthInfo($sys_user_id);

        $rules_str_list = array_extract($auth_list, 'rules');

        $rules_array_list = array_map("str2arr", $rules_str_list);

        $rules_array = [];

        foreach ($rules_array_list as $v) {

            $rules_array = array_merge($rules_array, $v);
        }

        // 当前授权会员的所有权限节点数组
        $rules_unique_array = array_unique($rules_array);

        $sub_sys_user_ids = $this->logicTenUser->getSubUserIds($sys_user_id);

        $sub_auth_list = $this->logicTenRoleAccess->getUserAuthInfo($sub_sys_user_ids);

        // 所有下级的角色id集合
        $sub_auth_ids = array_unique(array_extract($sub_auth_list, 'auth_id'));

        $this->updateAuthRulesByStandard($rules_unique_array, $sub_auth_ids);
    }

    /**
     * 递归更新下级权限节点，确保下级权限不能超越上级
     * 若上级某权限被收回，则下级对应的权限同样被收回
     * 按角色更新
     */
    public function updateSubRoleByMenu($role_id = 0)
    {

        $auth_list = $this->logicTenRoleMenu->getTenRoleAccessList(['ten_role_id' => $role_id]);

        $sys_user_arr_ids = array_unique(array_extract($auth_list, 'sys_user_id'));

        foreach ($sys_user_arr_ids as $id) {
            $this->updateSubAuthByUser($id);
        }
    }

    /**
     * 按参数$standard_rules_array权限节点数组标准，
     * 将参数$auth_ids角色ID数组下的权限节点全部更新
     */
    public function updateAuthRulesByStandard($standard_rules_array = [], $auth_ids = [])
    {
        $auth_list = $this->getTenRoleList(['id' => ['in', $auth_ids]]);
        foreach ($auth_list as $v) {

            $rules_arr = str2arr($v['rules']);

            foreach ($rules_arr as $kk => $vv) {
                if (!in_array($vv, $standard_rules_array)) {
                    unset($rules_arr[$kk]);
                }
            }

            $v['rules'] = arr2str(array_values($rules_arr));

            $this->modelTenRole->setFieldValue(['id' => $v['id']], 'rules', $v['rules']);
        }
    }
}
